<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <title>菜单管理</title>
    {% include 'system/common/header.html' %}
    <style>
        .menu-container {
            max-width: 1200px;
            margin: 20px auto;
            background: #f9f9f9;
            min-height: 600px;
        }
        
        .menu-tabs {
            background: #fff;
            border-bottom: 1px solid #ddd;
            padding: 0 20px;
        }
        
        .menu-tab {
            display: inline-block;
            padding: 15px 20px;
            text-decoration: none;
            color: #666;
            border-bottom: 3px solid transparent;
            cursor: pointer;
        }
        
        .menu-tab.active {
            color: #0073aa;
            border-bottom-color: #0073aa;
            background: #f9f9f9;
        }
        
        .menu-content {
            padding: 20px;
        }
        
        .menu-selection {
            background: #fff;
            padding: 20px;
            margin-bottom: 20px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .menu-selection select {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-right: 10px;
            min-width: 200px;
        }
        
        .menu-selection .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        .btn-primary {
            background: #0073aa;
            color: white;
        }
        
        .btn-primary:hover {
            background: #005a87;
        }
        
        .menu-selection .link {
            color: #0073aa;
            text-decoration: none;
        }
        
        .menu-selection .link:hover {
            text-decoration: underline;
        }
        
        .menu-selection .info {
            color: #0073aa;
            font-size: 14px;
            margin-top: 10px;
        }
        
        .menu-panels {
            display: flex;
            gap: 20px;
        }
        
        .menu-panel {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        /* 左侧面板：添加菜单项 - 占33% */
        .menu-panel:first-child {
            flex: 0 0 33%;
        }
        
        /* 右侧面板：菜单结构 - 占66% */
        .menu-panel:last-child {
            flex: 0 0 66%;
        }
        
        .menu-panel-header {
            background: #f9f9f9;
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
            font-weight: bold;
        }
        
        .menu-panel-body {
            padding: 20px;
        }
        
        .menu-item-section {
            margin-bottom: 15px;
            border: 1px solid #e5e5e5;
            border-radius: 4px;
        }
        
        .menu-item-section-header {
            background: #f9f9f9;
            padding: 10px 15px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #e5e5e5;
        }
        
        .menu-item-section-header:hover {
            background: #f0f0f0;
        }
        
        .menu-item-section-content {
            padding: 15px;
            display: none;
        }
        
        .menu-item-section.active .menu-item-section-content {
            display: block;
        }
        
        .menu-item-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .menu-item-option {
            padding: 8px 12px;
            border-bottom: 1px solid #eee;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .menu-item-option:hover {
            background: #f5f5f5;
        }
        
        .menu-item-option:last-child {
            border-bottom: none;
        }
        
        .menu-item-option input[type="checkbox"] {
            margin-right: 8px;
        }
        
        .menu-structure {
            min-height: 400px;
        }
        
        .menu-structure-header {
            margin-bottom: 15px;
        }
        
        .menu-structure-header input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        
        .menu-structure-instruction {
            color: #666;
            font-size: 14px;
            margin-bottom: 15px;
            line-height: 1.5;
        }
        
        .menu-structure-controls {
            margin-bottom: 15px;
            padding: 10px;
            background: #f9f9f9;
            border-radius: 4px;
        }
        
        .menu-structure-controls input[type="checkbox"] {
            margin-right: 8px;
        }
        
        .menu-items-container {
            min-height: 200px;
            border: 1px solid #ddd;
            border-radius: 4px;
            background: #fafafa;
            padding: 10px;
        }
        
        .menu-item {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 8px;
            cursor: move;
            position: relative;
        }
        
        .menu-item-header {
            padding: 10px 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
        }
        
        .menu-item-title {
            font-weight: bold;
            flex: 1;
        }
        
        .menu-item-type {
            color: #666;
            font-size: 12px;
            margin-left: 10px;
        }
        
        .menu-item-actions {
            display: flex;
            gap: 5px;
        }
        
        .menu-item-action {
            background: none;
            border: none;
            cursor: pointer;
            padding: 5px;
            color: #666;
            pointer-events: auto;
        }
        
        .menu-item-action:hover {
            color: #0073aa;
        }
        
        .menu-item-content {
            padding: 15px;
            display: none;
        }
        
        .menu-item.active .menu-item-content {
            display: block;
        }
        
        .menu-item-content input,
        .menu-item-content textarea {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        
        .menu-item-content label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .menu-item-content .form-group {
            margin-bottom: 15px;
        }
        
        .sub-menu {
            margin-left: 20px;
            border-left: 2px solid #ddd;
            padding-left: 15px;
            position: relative;
        }
        
        .sub-menu::before {
            content: '';
            position: absolute;
            left: -2px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #0073aa;
            opacity: 0.3;
        }
        
        .sub-menu .menu-item {
            margin-bottom: 5px;
        }
        
        .sub-menu-label {
            color: #666;
            font-size: 12px;
            margin-left: 10px;
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 3px;
        }
        
        .menu-actions {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid #ddd;
            text-align: right;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .custom-link-form {
            padding: 15px 0;
            display: block !important;
        }
        
        .custom-link-form .form-group {
            margin-bottom: 15px;
            display: block !important;
        }
        
        .custom-link-form label {
            display: block !important;
            margin-bottom: 5px;
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }
        
        .custom-link-form input[type="url"],
        .custom-link-form input[type="text"] {
            width: 100% !important;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
            display: block !important;
        }
        
        .custom-link-form input[type="url"]:focus,
        .custom-link-form input[type="text"]:focus {
            outline: none;
            border-color: #0073aa;
            box-shadow: 0 0 0 2px rgba(0, 115, 170, 0.2);
        }
        
        .custom-link-form .form-actions {
            text-align: right;
            margin-top: 20px;
            display: block !important;
        }
        
        .custom-link-form .btn {
            padding: 8px 16px;
            font-size: 14px;
            display: inline-block !important;
        }
        
        .menu-item-placeholder {
            border: 2px dashed #ddd;
            background: #f9f9f9;
            height: 50px;
            margin: 10px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #666;
        }
        
        /* 拖拽相关样式 */
        .menu-item {
            position: relative;
            transition: all 0.2s ease;
        }

        .menu-item.dragging {
            opacity: 0.5;
            transform: rotate(5deg);
            z-index: 1000;
        }

        .menu-item.drag-before {
            border-top: 3px solid #0073aa;
            margin-top: 5px;
        }

        .menu-item.drag-after {
            border-bottom: 3px solid #28a745;
            margin-bottom: 5px;
        }

        .menu-item.drag-child {
            background-color: #fff3cd;
            border: 2px dashed #ffc107;
        }

        /* 子菜单样式 */
        .sub-menu {
            margin-left: 20px;
            border-left: 2px solid #e9ecef;
            padding-left: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            margin-top: 5px;
            margin-bottom: 5px;
        }

        .sub-menu .menu-item {
            margin-bottom: 5px;
        }

        .sub-menu-label {
            background: #6c757d;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 11px;
            margin-left: 8px;
        }

        /* 拖拽手柄样式 */
        .drag-handle {
            cursor: move;
            color: #999;
            font-size: 16px;
            margin-right: 10px;
            user-select: none;
        }

        .drag-handle:hover {
            color: #666;
        }
        /* 页面标签页样式 */
        .page-tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 10px;
        }
        
        .page-tab {
            padding: 8px 16px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 14px;
            color: #666;
        }
        
        .page-tab:hover {
            color: #0073aa;
        }
        
        .page-tab.active {
            color: #0073aa;
            border-bottom-color: #0073aa;
            font-weight: 500;
        }
        
        .page-tab-content {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .page-list {
            margin-bottom: 10px;
        }
        
        .page-item {
            display: flex;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .page-item:last-child {
            border-bottom: none;
        }
        
        .page-item input[type="checkbox"] {
            margin-right: 8px;
        }
        
        .page-item label {
            cursor: pointer;
            font-size: 14px;
            color: #333;
            flex: 1;
        }
        
        .page-item label:hover {
            color: #0073aa;
        }
        
        .page-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-top: 1px solid #ddd;
        }
        
        .select-all {
            display: flex;
            align-items: center;
        }
        
        .select-all input[type="checkbox"] {
            margin-right: 6px;
        }
        
        .select-all label {
            font-size: 14px;
            color: #666;
            cursor: pointer;
        }
        
        .search-box {
            margin-bottom: 10px;
        }
        
        .search-box input {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .search-box input:focus {
            outline: none;
            border-color: #0073aa;
            box-shadow: 0 0 0 2px rgba(0, 115, 170, 0.2);
        }

        /* 文章标签页样式 */
        .post-tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 10px;
        }
        
        .post-tab {
            padding: 8px 16px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 14px;
            color: #666;
        }
        
        .post-tab:hover {
            color: #0073aa;
        }
        
        .post-tab.active {
            color: #0073aa;
            border-bottom-color: #0073aa;
            font-weight: 500;
        }
        
        .post-tab-content {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .post-list {
            margin-bottom: 10px;
        }
        
        .post-item {
            display: flex;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .post-item:last-child {
            border-bottom: none;
        }
        
        .post-item input[type="checkbox"] {
            margin-right: 8px;
        }
        
        .post-item label {
            cursor: pointer;
            font-size: 14px;
            color: #333;
            flex: 1;
        }
        
        .post-item label:hover {
            color: #0073aa;
        }
        
        .post-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-top: 1px solid #ddd;
        }

        /* 分类目录标签页样式 */
        .category-tabs {
            display: flex;
            border-bottom: 1px solid #ddd;
            margin-bottom: 10px;
        }
        
        .category-tab {
            padding: 8px 16px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            font-size: 14px;
            color: #666;
        }
        
        .category-tab:hover {
            color: #0073aa;
        }
        
        .category-tab.active {
            color: #0073aa;
            border-bottom-color: #0073aa;
            font-weight: 500;
        }
        
        .category-tab-content {
            max-height: 300px;
            overflow-y: auto;
        }
        
        .category-list {
            margin-bottom: 10px;
        }
        
        .category-item {
            display: flex;
            align-items: center;
            padding: 8px 0;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .category-item:last-child {
            border-bottom: none;
        }
        
        .category-item input[type="checkbox"] {
            margin-right: 8px;
        }
        
        .category-item label {
            cursor: pointer;
            font-size: 14px;
            color: #333;
            flex: 1;
        }
        
        .category-item label:hover {
            color: #0073aa;
        }
        
        .category-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-top: 1px solid #ddd;
        }
        
        /* 统一所有"添加至菜单"按钮样式 */
        .page-actions .btn,
        .post-actions .btn,
        .category-actions .btn,
        .custom-link-form .btn,
        .menu-actions .btn {
            padding: 8px 16px;
            font-size: 14px;
            background: #0073aa;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            display: inline-block;
        }
        
        .page-actions .btn:hover,
        .post-actions .btn:hover,
        .category-actions .btn:hover,
        .custom-link-form .btn:hover,
        .menu-actions .btn:hover {
            background: #005a87;
        }
        
        /* 删除按钮特殊样式 */
        .menu-actions .btn-danger {
            background: #dc3545;
            margin-left: 10px;
        }
        
        .menu-actions .btn-danger:hover {
            background: #c82333;
        }
        
        /* Target字段样式 - 与其他字段保持一致 */
        .menu-item-content select[name="target"],
        .custom-link-form select[name="target"] {
            width: 100% !important;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
            display: block !important;
            background-color: #fff;
            color: #333;
            cursor: pointer;
        }
        
        .menu-item-content select[name="target"]:focus,
        .custom-link-form select[name="target"]:focus {
            outline: none;
            border-color: #0073aa;
            box-shadow: 0 0 0 2px rgba(0, 115, 170, 0.2);
        }
        
        .menu-item-content select[name="target"]:hover,
        .custom-link-form select[name="target"]:hover {
            border-color: #0073aa;
        }
        
        /* 确保所有表单字段样式一致 */
        .menu-item-content input[type="text"],
        .menu-item-content input[type="url"],
        .menu-item-content textarea {
            width: 100% !important;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
            display: block !important;
        }
        
        .menu-item-content input[type="text"]:focus,
        .menu-item-content input[type="url"]:focus,
        .menu-item-content textarea:focus {
            outline: none;
            border-color: #0073aa;
            box-shadow: 0 0 0 2px rgba(0, 115, 170, 0.2);
        }
    </style>
</head>
<body class="ppress-container">
    <div class="menu-container">
        <!-- 菜单标签页 -->
        <div class="menu-tabs">
            <div class="menu-tab active" data-tab="edit">编辑菜单</div>
            <div class="menu-tab" data-tab="locations">管理位置</div>
        </div>

        <!-- 菜单内容区域 -->
        <div class="menu-content">
            <!-- 编辑菜单标签页内容 -->
            <div class="edit-tab-content">
                <!-- 菜单选择区域 -->
                <div class="menu-selection">
                    <label for="menuSelect">选择要编辑的菜单:</label>
                    <select id="menuSelect">
                        <option value="primary">primary (主要)</option>
                        <option value="footer">footer (页脚)</option>
                        <option value="mobile">mobile (移动端)</option>
                    </select>
                    <button class="btn btn-primary" onclick="loadMenu()">选择</button>
                    <a href="#" class="link" onclick="createNewMenu()">或创建一个新菜单。</a>
                    <div class="info">不要忘记保存您的更改!</div>
                </div>

                <!-- 菜单编辑面板 -->
                <div class="menu-panels">
                    <!-- 左侧：添加菜单项 -->
                    <div class="menu-panel">
                        <div class="menu-panel-header">添加菜单项</div>
                        <div class="menu-panel-body">
                            <!-- 页面 -->
                            <div class="menu-item-section">
                                <div class="menu-item-section-header" onclick="toggleSection(this)">
                                    <span>页面</span>
                                    <span class="toggle-icon">▼</span>
                                </div>
                                <div class="menu-item-section-content">
                                    <!-- 页面标签页 -->
                                    <div class="page-tabs">
                                        <div class="page-tab active" data-tab="recent" onclick="switchPageTab(this, 'recent')">最近</div>
                                        <div class="page-tab" data-tab="all" onclick="switchPageTab(this, 'all')">查看所有</div>
                                        <div class="page-tab" data-tab="search" onclick="switchPageTab(this, 'search')">搜索</div>
                                    </div>

                                    <!-- 最近页面 -->
                                    <div class="page-tab-content" id="recent-pages">
                                        <div class="page-list">
                                            {% for page in get_pages() %}
                                            <div class="page-item">
                                                <input type="checkbox" id="page-all-home" data-type="page" data-id="{{ page.slug }}" data-title="{{ page.title }}">
                                                <label for="page-all-home">{{ page.title }}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="page-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-recent" onclick="toggleSelectAll('recent')">
                                                <label for="select-all-recent">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedPages('recent')">添加至菜单</button>
                                        </div>
                                    </div>

                                    <!-- 查看所有页面 -->
                                    <div class="page-tab-content" id="all-pages" style="display: none;">
                                        <div class="page-list">
                                            {% for page in get_pages() %}
                                            <div class="page-item">
                                                <input type="checkbox" id="page-all-home" data-type="page" data-id="{{ page.slug }}" data-title="{{ page.title }}">
                                                <label for="page-all-home">{{ page.title }}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="page-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-all" onclick="toggleSelectAll('all')">
                                                <label for="select-all-all">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedPages('all')">添加至菜单</button>
                                        </div>
                                    </div>

                                    <!-- 搜索页面 -->
                                    <div class="page-tab-content" id="search-pages" style="display: none;">
                                        <div class="search-box">
                                            <input type="text" id="page-search-input" placeholder="搜索页面..." onkeyup="searchPages(this.value)">
                                        </div>
                                        <div class="page-list" id="search-results">
                                            {% for page in get_pages() %}
                                            <div class="page-item">
                                                <input type="checkbox" id="page-all-home" data-type="page" data-id="{{ page.slug }}" data-title="{{ page.title }}">
                                                <label for="page-all-home">{{ page.title }}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="page-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-search" onclick="toggleSelectAll('search')">
                                                <label for="select-all-search">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedPages('search')">添加至菜单</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 文章 -->
                            <div class="menu-item-section">
                                <div class="menu-item-section-header" onclick="toggleSection(this)">
                                    <span>文章</span>
                                    <span class="toggle-icon">▼</span>
                                </div>
                                <div class="menu-item-section-content">
                                    <!-- 文章标签页 -->
                                    <div class="post-tabs">
                                        <div class="post-tab active" data-tab="recent" onclick="switchPostTab(this, 'recent')">最近</div>
                                        <div class="post-tab" data-tab="all" onclick="switchPostTab(this, 'all')">查看所有</div>
                                        <div class="post-tab" data-tab="search" onclick="switchPostTab(this, 'search')">搜索</div>
                                    </div>

                                    <!-- 最近文章 -->
                                    <div class="post-tab-content" id="recent-posts">
                                        <div class="post-list">
                                            {% for post in get_articles() %}
                                            <div class="post-item">
                                                <input type="checkbox" id="post-all-home" data-type="post" data-id="{{ post.slug }}" data-title="{{ post.title }}">
                                                <label for="home-all-home">{{ post.title }}</label>
                                            </div>
                                            {% endfor %}

                                        </div>
                                        <div class="post-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-recent-posts" onclick="toggleSelectAllPosts('recent')">
                                                <label for="select-all-recent-posts">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedPosts('recent')">添加至菜单</button>
                                        </div>
                                    </div>

                                    <!-- 查看所有文章 -->
                                    <div class="post-tab-content" id="all-posts" style="display: none;">
                                        <div class="post-list">
                                           {% for post in get_articles() %}
                                            <div class="post-item">
                                                <input type="checkbox" id="post-all-home" data-type="post" data-id="{{ post.slug }}" data-title="{{ post.title }}">
                                                <label for="home-all-home">{{ post.title }}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="post-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-all-posts" onclick="toggleSelectAllPosts('all')">
                                                <label for="select-all-all-posts">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedPosts('all')">添加至菜单</button>
                                        </div>
                                    </div>

                                    <!-- 搜索文章 -->
                                    <div class="post-tab-content" id="search-posts" style="display: none;">
                                        <div class="search-box">
                                            <input type="text" id="post-search-input" placeholder="搜索文章..." onkeyup="searchPosts(this.value)">
                                        </div>
                                        <div class="post-list" id="post-search-results">
                                            {% for post in get_articles() %}
                                            <div class="post-item">
                                                <input type="checkbox" id="post-all-home" data-type="post" data-id="{{ post.slug }}" data-title="{{ post.title }}">
                                                <label for="home-all-home">{{ post.title }}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="post-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-search-posts" onclick="toggleSelectAllPosts('search')">
                                                <label for="select-all-search-posts">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedPosts('search')">添加至菜单</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 自定义链接 -->
                            <div class="menu-item-section">
                                <div class="menu-item-section-header" onclick="toggleSection(this)">
                                    <span>自定义链接</span>
                                    <span class="toggle-icon">▼</span>
                                </div>
                                <div class="menu-item-section-content">
                                    <div class="custom-link-form">
                                        <div class="form-group">
                                            <label for="customLinkUrl">网址:</label>
                                            <input type="url" id="customLinkUrl" value="https://" placeholder="https://">
                                        </div>
                                        <div class="form-group">
                                            <label for="customLinkText">链接文字:</label>
                                            <input type="text" id="customLinkText" placeholder="输入链接文字">
                                        </div>
                                        <div class="form-actions">
                                            <button class="btn btn-primary" onclick="addCustomLink()">添加至菜单</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 分类目录 -->
                            <div class="menu-item-section">
                                <div class="menu-item-section-header" onclick="toggleSection(this)">
                                    <span>分类目录</span>
                                    <span class="toggle-icon">▼</span>
                                </div>
                                <div class="menu-item-section-content">
                                    <!-- 分类目录标签页 -->
                                    <div class="category-tabs">
                                        <div class="category-tab active" data-tab="recent" onclick="switchCategoryTab(this, 'recent')">最近</div>
                                        <div class="category-tab" data-tab="all" onclick="switchCategoryTab(this, 'all')">查看所有</div>
                                        <div class="category-tab" data-tab="search" onclick="switchCategoryTab(this, 'search')">搜索</div>
                                    </div>

                                    <!-- 最近分类目录 -->
                                    <div class="category-tab-content" id="recent-categories">
                                        <div class="category-list">
                                            {% for category in get_categories() %}
                                            <div class="category-item">
                                                <input type="checkbox" id="category-{{ category.alias }}" data-type="category" data-id="{{ category.alias }}" data-title="{{ category.title }}">
                                                <label for="category-{{ category.alias }}">{{ category.title }}</label>
                                            </div>
                                            {% endfor %}

                                        </div>
                                        <div class="category-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-recent-categories" onclick="toggleSelectAllCategories('recent')">
                                                <label for="select-all-recent-categories">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedCategories('recent')">添加至菜单</button>
                                        </div>
                                    </div>

                                    <!-- 查看所有分类目录 -->
                                    <div class="category-tab-content" id="all-categories" style="display: none;">
                                        <div class="category-list">
                                            {% for category in get_categories() %}
                                            <div class="category-item">
                                                <input type="checkbox" id="category-{{ category.alias }}" data-type="category" data-id="{{ category.alias }}" data-title="{{ category.title }}">
                                                <label for="category-{{ category.alias }}">{{ category.title }}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="category-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-all-categories" onclick="toggleSelectAllCategories('all')">
                                                <label for="select-all-all-categories">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedCategories('all')">添加至菜单</button>
                                        </div>
                                    </div>

                                    <!-- 搜索分类目录 -->
                                    <div class="category-tab-content" id="search-categories" style="display: none;">
                                        <div class="search-box">
                                            <input type="text" id="category-search-input" placeholder="搜索分类目录..." onkeyup="searchCategories(this.value)">
                                        </div>
                                        <div class="category-list" id="category-search-results">
                                            {% for category in get_categories() %}
                                            <div class="category-item">
                                                <input type="checkbox" id="category-search-${category.alias}" data-type="category" data-id="${category.alias}" data-title="${category.title}">
                                                <label for="category-search-${category.alias}">${category.title}</label>
                                            </div>
                                            {% endfor %}
                                        </div>
                                        <div class="category-actions">
                                            <div class="select-all">
                                                <input type="checkbox" id="select-all-search-categories" onclick="toggleSelectAllCategories('search')">
                                                <label for="select-all-search-categories">全选</label>
                                            </div>
                                            <button class="btn btn-primary" onclick="addSelectedCategories('search')">添加至菜单</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 右侧：菜单结构 -->
                    <div class="menu-panel">
                        <div class="menu-panel-header">菜单结构</div>
                        <div class="menu-panel-body">
                            <div class="menu-structure">
                                <div class="menu-structure-header">
                                    <input type="text" id="menuName" value="primary" placeholder="菜单名称">
                                </div>

                                <div class="menu-structure-instruction">
                                    将各个项目拖到您喜欢的顺序。点击项目右边的箭头可显示其他配置选项。
                                    <br><br>
                                    <strong>拖拽操作说明：</strong>
                                    <ul style="margin: 10px 0; padding-left: 20px; color: #666;">
                                        <li>拖拽到菜单项上方显示蓝色：放置到该菜单项之前</li>
                                        <li>拖拽到菜单项下方显示绿色：放置到该菜单项之后</li>
                                        <li>拖拽到菜单项中间：创建子菜单</li>
                                        <li>按住Shift键拖拽到中间：将子菜单项提升为顶级菜单项</li>
                                    </ul>
                                </div>


                                <div class="menu-items-container" id="menuItemsContainer">
                                    <!-- 示例菜单项 -->

                                </div>

                                <div class="menu-actions">
                                    <button class="btn btn-primary" onclick="saveMenu()">保存菜单</button>
                                    <button class="btn btn-danger" onclick="deleteMenu()">删除菜单</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 管理位置标签页内容 -->
            <div class="locations-tab-content" style="display: none;">
                <div style="text-align: center; padding: 50px;">
                    <h3>管理位置</h3>
                    <p>此功能暂未实现</p>
                    <div style="margin-top: 20px;">
                        <p>在这里可以管理菜单在不同位置（如头部、页脚、侧边栏等）的显示。</p>
                        <p>功能包括：</p>
                        <ul style="text-align: left; max-width: 400px; margin: 20px auto;">
                            <li>分配菜单到不同位置</li>
                            <li>设置菜单显示条件</li>
                            <li>管理菜单优先级</li>
                            <li>预览菜单效果</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let currentMenu = 'primary';
        let menuItems = [];
        let nextItemId = 7;

        // 拖拽相关变量
        let draggedElement = null;
        let dropTarget = null;
        let dropPosition = null;

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initDragAndDrop();
            
            // 加载菜单列表
            loadMenuList();
            
            // 为菜单选择下拉框添加change事件监听器
            const menuSelect = document.getElementById('menuSelect');
            if (menuSelect) {
                menuSelect.addEventListener('change', function() {
                    currentMenu = this.value;
                    loadMenu();
                });
                
                // 页面加载时自动加载第一个菜单
                if (menuSelect.value) {
                    currentMenu = menuSelect.value;
                    loadMenu();
                }
            }
        });

        // 切换标签页
        document.querySelectorAll('.menu-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                document.querySelectorAll('.menu-tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');

                const tabName = this.getAttribute('data-tab');
                if (tabName === 'locations') {
                    showLocationsTab();
                } else {
                    showEditTab();
                }
            });
        });

        // 显示编辑标签页
        function showEditTab() {
            const menuContent = document.querySelector('.menu-content');
            const editContent = document.querySelector('.edit-tab-content');
            const locationsContent = document.querySelector('.locations-tab-content');

            if (editContent) {
                editContent.style.display = 'block';
            }
            if (locationsContent) {
                locationsContent.style.display = 'none';
            }
        }

        // 显示位置管理标签页
        function showLocationsTab() {
            const menuContent = document.querySelector('.menu-content');
            const editContent = document.querySelector('.edit-tab-content');
            const locationsContent = document.querySelector('.locations-tab-content');

            if (editContent) {
                editContent.style.display = 'none';
            }
            if (locationsContent) {
                locationsContent.style.display = 'block';
            }
        }

        // 保存当前菜单状态
        function saveMenuState() {
            const container = document.getElementById('menuItemsContainer');
            if (container) {
                return {
                    html: container.innerHTML,
                    menuItems: menuItems,
                    currentMenu: currentMenu,
                    nextItemId: nextItemId
                };
            }
            return null;
        }

        // 恢复菜单状态
        function restoreMenuState(state) {
            if (state) {
                const container = document.getElementById('menuItemsContainer');
                if (container) {
                    container.innerHTML = state.html;
                    menuItems = state.menuItems || [];
                    currentMenu = state.currentMenu || 'primary';
                    nextItemId = state.nextItemId || 7;

                    // 重新初始化拖拽功能
                    initDragAndDrop();
                }
            }
        }

        // 切换菜单项部分展开/收起
        function toggleSection(header) {
            console.log('toggleSection called', header);
            const section = header.parentElement;
            const content = section.querySelector('.menu-item-section-content');
            const icon = header.querySelector('.toggle-icon');

            console.log('section:', section);
            console.log('content:', content);
            console.log('icon:', icon);
            console.log('current active state:', section.classList.contains('active'));

            if (section.classList.contains('active')) {
                section.classList.remove('active');
                icon.textContent = '▼';
                console.log('Section collapsed');
            } else {
                section.classList.add('active');
                icon.textContent = '▲';
                console.log('Section expanded');
            }
        }

        // 添加自定义链接
        function addCustomLink() {
            const url = document.getElementById('customLinkUrl').value;
            const text = document.getElementById('customLinkText').value;

            if (!url || url === 'https://') {
                return;
            }

            if (!text.trim()) {
                return;
            }

            const menuItem = {
                id: nextItemId++,
                type: 'custom-link',
                title: text,
                url: url,
                navigation_label: text,
                target: '_self', // 默认在当前窗口打开
                icon: '',
                title_attribute: '',
                css_classes: '',
                xfn: '',
                description: '',
                parent: null
            };

            addMenuItemToStructure(menuItem);

            // 清空表单
            document.getElementById('customLinkUrl').value = 'https://';
            document.getElementById('customLinkText').value = '';
        }

        // 添加选中的项目
        function addSelectedItems() {
            const checkedItems = document.querySelectorAll('.menu-item-option input[type="checkbox"]:checked');

            checkedItems.forEach(item => {
                const type = item.getAttribute('data-type');
                const id = item.getAttribute('data-id');
                const title = item.getAttribute('data-title');

                const menuItem = {
                    id: nextItemId++,
                    type: type,
                    title: title,
                    url: getItemUrl(type, id),
                    navigation_label: title,
                    target: '_self', // 默认在当前窗口打开
                    icon: '',
                    title_attribute: '',
                    css_classes: '',
                    xfn: '',
                    description: '',
                    parent: null
                };

                addMenuItemToStructure(menuItem);

                // 取消选中
                item.checked = false;
            });
        }

        // 获取项目URL
        function getItemUrl(type, id) {
            switch(type) {
                case 'page':
                    return `/page/${id}`;
                case 'post':
                    return `/post/${id}`;
                case 'category':
                    return `/category/${id}`;
                default:
                    return '#';
            }
        }

        // 添加菜单项到结构
        function addMenuItemToStructure(menuItem) {
            const container = document.getElementById('menuItemsContainer');
            const menuItemElement = createMenuItemElement(menuItem);
            container.appendChild(menuItemElement);

            // 保存到数据
            menuItems.push(menuItem);
        }

        // 创建菜单项元素
        function createMenuItemElement(menuItem) {
            const element = document.createElement('div');
            element.className = 'menu-item';
            element.setAttribute('data-id', menuItem.id);
            element.setAttribute('data-type', menuItem.type);

            const typeText = getTypeText(menuItem.type);
            const navigationLabel = menuItem.navigation_label || menuItem.title;
            const target = menuItem.target || '_self';

            element.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle" style="cursor: move; margin-right: 10px; color: #999;">⋮⋮</div>
                    <div class="menu-item-title">${menuItem.title}</div>
                    <div class="menu-item-type">${typeText}</div>
                    <div class="menu-item-actions">
                        <button class="menu-item-action" onclick="toggleMenuItem(this)" title="展开/收起">▼</button>
                        <button class="menu-item-action" onclick="removeMenuItem(this)" title="删除">×</button>
                    </div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="${navigationLabel}">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="${menuItem.url}">
                    </div>
                    <div class="form-group">
                        <label>图标:</label>
                        <input type="text" placeholder="图标类名或URL" value="${menuItem.icon || ''}">
                    </div>
                    <div class="form-group">
                        <label>Target:</label>
                        <select name="target">
                            <option value="_self" ${target === '_self' ? 'selected' : ''}>当前窗口 (_self)</option>
                            <option value="_blank" ${target === '_blank' ? 'selected' : ''}>新窗口 (_blank)</option>
                            <option value="_parent" ${target === '_parent' ? 'selected' : ''}>父窗口 (_parent)</option>
                            <option value="_top" ${target === '_top' ? 'selected' : ''}>顶级窗口 (_top)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>标题属性:</label>
                        <input type="text" placeholder="鼠标悬停时显示的文本" value="${menuItem.title_attribute || ''}">
                    </div>
                    <div class="form-group">
                        <label>CSS类:</label>
                        <input type="text" placeholder="CSS类名" value="${menuItem.css_classes || ''}">
                    </div>
                    <div class="form-group">
                        <label>链接关系(XFN):</label>
                        <input type="text" placeholder="链接关系" value="${menuItem.xfn || ''}">
                    </div>
                    <div class="form-group">
                        <label>描述:</label>
                        <textarea rows="3" placeholder="菜单项描述">${menuItem.description || ''}</textarea>
                    </div>
                </div>
            `;

            return element;
        }

        // 获取类型文本
        function getTypeText(type) {
            switch(type) {
                case 'page':
                    return '页面';
                case 'post':
                    return '文章';
                case 'category':
                    return '分类目录';
                case 'custom-link':
                    return '自定义链接';
                default:
                    return '未知';
            }
        }

        // 切换菜单项展开/收起
        function toggleMenuItem(button) {
            const menuItem = button.closest('.menu-item');
            const content = menuItem.querySelector('.menu-item-content');

            if (menuItem.classList.contains('active')) {
                menuItem.classList.remove('active');
                button.textContent = '▼';
            } else {
                menuItem.classList.add('active');
                button.textContent = '▲';
            }
        }

        // 删除菜单项
        function removeMenuItem(button) {
            const menuItem = button.closest('.menu-item');
            const itemId = parseInt(menuItem.getAttribute('data-id'));

            if (confirm('确定要删除这个菜单项吗？')) {
                menuItem.remove();

                // 从数据中移除
                menuItems = menuItems.filter(item => item.id !== itemId);
            }
        }

        // 初始化拖拽功能
        function initDragAndDrop() {
            const container = document.getElementById('menuItemsContainer');

            // 为现有菜单项添加拖拽功能
            container.querySelectorAll('.menu-item').forEach(item => {
                addDragListeners(item);
            });

            // 监听新添加的菜单项
            const observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    mutation.addedNodes.forEach(function(node) {
                        if (node.nodeType === 1 && node.classList.contains('menu-item')) {
                            addDragListeners(node);
                        }
                    });
                });
            });

            observer.observe(container, { childList: true });
        }

        // 添加拖拽监听器
        function addDragListeners(element) {
            element.draggable = true;

            element.addEventListener('dragstart', function(e) {
                console.log('开始拖拽:', this.querySelector('.menu-item-title').textContent);

                draggedElement = this;
                this.classList.add('dragging');

                e.dataTransfer.setData('text/plain', this.getAttribute('data-id'));
                e.dataTransfer.effectAllowed = 'move';
            });

            element.addEventListener('dragend', function() {
                console.log('结束拖拽:', this.querySelector('.menu-item-title').textContent);

                this.classList.remove('dragging');
                draggedElement = null;
                dropTarget = null;
                dropPosition = null;

                // 清理所有拖拽样式
                document.querySelectorAll('.drag-before, .drag-after, .drag-child').forEach(el => {
                    el.classList.remove('drag-before', 'drag-after', 'drag-child');
                });
            });

            element.addEventListener('dragover', function(e) {
                e.preventDefault();
                e.dataTransfer.dropEffect = 'move';

                if (!draggedElement || draggedElement === this) return;

                dropTarget = this;
                const rect = this.getBoundingClientRect();
                const centerY = rect.top + rect.height / 2;

                // 移除之前的样式
                this.classList.remove('drag-before', 'drag-after', 'drag-child');

                // 判断拖拽位置
                if (e.clientY < centerY - 10) {
                    dropPosition = 'before';
                    this.classList.add('drag-before');
                } else if (e.clientY > centerY + 10) {
                    dropPosition = 'after';
                    this.classList.add('drag-after');
                } else {
                    dropPosition = 'child';
                    this.classList.add('drag-child');
                }
            });

            element.addEventListener('dragleave', function(e) {
                const rect = this.getBoundingClientRect();
                if (e.clientX < rect.left || e.clientX > rect.right ||
                    e.clientY < rect.top || e.clientY > rect.bottom) {
                    this.classList.remove('drag-before', 'drag-after', 'drag-child');
                }
            });

            element.addEventListener('drop', function(e) {
                e.preventDefault();

                if (!draggedElement || draggedElement === this) return;

                console.log('处理拖拽放置:', {
                    dragged: draggedElement.querySelector('.menu-item-title').textContent,
                    target: this.querySelector('.menu-item-title').textContent,
                    position: dropPosition
                });

                // 移除样式
                this.classList.remove('drag-before', 'drag-after', 'drag-child');

                // 处理放置
                handleDrop(this, draggedElement, dropPosition, e);
            });
        }

        // 处理拖拽放置
        function handleDrop(targetElement, draggedElement, position, event) {
            const container = document.getElementById('menuItemsContainer');

            console.log('处理放置:', {
                position,
                shiftKey: event.shiftKey,
                altKey: event.altKey
            });

            // 获取拖拽元素及其所有子菜单
            const draggedItems = getDraggedItemsWithChildren(draggedElement);

            switch (position) {
                case 'before':
                    // 放置到目标之前
                    draggedItems.forEach(item => {
                        container.insertBefore(item, targetElement);
                    });
                    console.log('放置到目标之前');
                    break;

                case 'after':
                    // 放置到目标之后
                    const targetNextSibling = targetElement.nextSibling;
                    draggedItems.forEach(item => {
                        container.insertBefore(item, targetNextSibling);
                    });
                    console.log('放置到目标之后');
                    break;

                case 'child':
                    // 创建子菜单或提升为顶级菜单项
                    if (event.shiftKey || event.altKey) {
                        // 提升为顶级菜单项
                        promoteToTopLevel(draggedElement);
                        console.log('提升为顶级菜单项');
                    } else {
                        // 创建子菜单
                        createSubmenu(targetElement, draggedElement);
                        console.log('创建子菜单');
                    }
                    break;
            }

            // 修复子菜单不关联问题
            fixSubmenuDisconnection();
            
            // 更新菜单数据
            updateMenuData();
        }

        // 获取拖拽元素及其所有子菜单项
        function getDraggedItemsWithChildren(draggedElement) {
            const items = [draggedElement];
            
            // 查找拖拽元素后面的子菜单容器
            let nextElement = draggedElement.nextElementSibling;
            while (nextElement && nextElement.classList.contains('sub-menu')) {
                // 将整个子菜单容器添加到数组中
                items.push(nextElement);
                nextElement = nextElement.nextElementSibling;
            }
            
            return items;
        }

        // 创建子菜单
        function createSubmenu(parentElement, childElement) {
            console.log('=== 创建子菜单 ===');
            console.log('父元素:', parentElement.querySelector('.menu-item-title').textContent);
            console.log('子元素:', childElement.querySelector('.menu-item-title').textContent);
            
            // 获取子元素及其所有子菜单容器
            const childItems = getDraggedItemsWithChildren(childElement);
            console.log('要移动的项目数量:', childItems.length);
            
            // 如果子元素已经在某个子菜单中，先移除它
            const existingSubmenu = childElement.closest('.sub-menu');
            if (existingSubmenu) {
                console.log('子元素已在子菜单中，先移除');
                childItems.forEach(item => {
                    existingSubmenu.parentNode.insertBefore(item, existingSubmenu);
                });
                if (existingSubmenu.children.length === 0) {
                    existingSubmenu.remove();
                }
            }

            // 检查父元素是否已经有子菜单容器
            let submenuContainer = parentElement.nextElementSibling;
            console.log('父元素下一个兄弟:', submenuContainer?.className);

            if (!submenuContainer || !submenuContainer.classList.contains('sub-menu')) {
                console.log('创建新的子菜单容器');
                submenuContainer = document.createElement('div');
                submenuContainer.className = 'sub-menu';
                parentElement.parentNode.insertBefore(submenuContainer, parentElement.nextSibling);
            } else {
                console.log('使用现有子菜单容器');
                console.log('现有子菜单中的项目数量:', submenuContainer.children.length);
            }

            // 将子元素及其子菜单容器移动到新的子菜单容器中
            // 注意：这里应该追加到现有子菜单的末尾，而不是替换
            childItems.forEach(item => {
                // 如果item是子菜单容器，需要将其中的菜单项移动到目标容器
                if (item.classList.contains('sub-menu')) {
                    console.log('移动子菜单容器中的项目');
                    const submenuItems = Array.from(item.children);
                    submenuItems.forEach(subItem => {
                        submenuContainer.appendChild(subItem);
                    });
                    // 移除空的子菜单容器
                    item.remove();
                } else {
                    // 直接移动菜单项
                    submenuContainer.appendChild(item);
                }
            });

            // 更新子菜单标签
            updateSubmenuLabels();

            console.log('移动完成');
            console.log('最终子菜单中的项目数量:', submenuContainer.children.length);
            console.log(`已将 "${childElement.querySelector('.menu-item-title').textContent}" 及其子菜单设为 "${parentElement.querySelector('.menu-item-title').textContent}" 的子项`);
        }

        // 提升为顶级菜单项
        function promoteToTopLevel(element) {
            const container = document.getElementById('menuItemsContainer');

            // 获取元素及其所有子菜单
            const childItems = getDraggedItemsWithChildren(element);

            // 如果元素在子菜单中，将其及其子菜单移出
            const submenu = element.closest('.sub-menu');
            if (submenu) {
                childItems.forEach(item => {
                    submenu.parentNode.insertBefore(item, submenu);
                });
                // 如果子菜单为空，删除它
                if (submenu.children.length === 0) {
                    submenu.remove();
                }
            }

            // 移除子菜单标签
            childItems.forEach(item => {
                if (item.classList.contains('menu-item')) {
                    const subLabel = item.querySelector('.sub-menu-label');
                    if (subLabel) {
                        subLabel.remove();
                    }
                }
            });

            console.log(`已将 "${element.querySelector('.menu-item-title').textContent}" 及其子菜单提升为顶级菜单项`);
        }

        // 更新子菜单标签
        function updateSubmenuLabels() {
            document.querySelectorAll('.sub-menu .menu-item-type').forEach(label => {
                if (!label.querySelector('.sub-menu-label')) {
                    const subLabel = document.createElement('span');
                    subLabel.className = 'sub-menu-label';
                    subLabel.textContent = '子项目';
                    label.appendChild(subLabel);
                }
            });
        }

        // 更新菜单数据
        function updateMenuData() {
            const container = document.getElementById('menuItemsContainer');
            let newMenuItems = [];
            let itemId = 1;

            // 递归构建菜单数据结构
            function buildMenuStructure(parentElement) {
                const items = [];
                
                // 遍历父元素下的直接子菜单项
                let currentElement = parentElement.firstElementChild;
                while (currentElement) {
                    if (currentElement.classList.contains('menu-item')) {
                        // 获取菜单项的基本信息
                        const menuItem = {
                            id: parseInt(currentElement.getAttribute('data-id')),
                            type: currentElement.getAttribute('data-type'),
                            title: currentElement.querySelector('.menu-item-title').textContent,
                            url: currentElement.querySelector('input[type="url"]')?.value || '#',
                            order: itemId++
                        };
                        
                        // 获取导航标签（独立字段）
                        const navigationLabelInput = currentElement.querySelector('input[type="text"]');
                        if (navigationLabelInput) {
                            menuItem.navigation_label = navigationLabelInput.value;
                        }
                        
                        // 获取图标
                        const iconInput = currentElement.querySelector('input[placeholder="图标类名或URL"]');
                        if (iconInput) {
                            menuItem.icon = iconInput.value;
                        }
                        
                        // 获取Target
                        const targetSelect = currentElement.querySelector('select[name="target"]');
                        if (targetSelect) {
                            menuItem.target = targetSelect.value;
                        }
                        
                        // 获取标题属性
                        const titleAttributeInput = currentElement.querySelector('input[placeholder="鼠标悬停时显示的文本"]');
                        if (titleAttributeInput) {
                            menuItem.title_attribute = titleAttributeInput.value;
                        }
                        
                        // 获取CSS类
                        const cssClassesInput = currentElement.querySelector('input[placeholder="CSS类名"]');
                        if (cssClassesInput) {
                            menuItem.css_classes = cssClassesInput.value;
                        }
                        
                        // 获取链接关系(XFN)
                        const xfnInput = currentElement.querySelector('input[placeholder="链接关系"]');
                        if (xfnInput) {
                            menuItem.xfn = xfnInput.value;
                        }
                        
                        // 获取描述
                        const descriptionTextarea = currentElement.querySelector('textarea[placeholder="菜单项描述"]');
                        if (descriptionTextarea) {
                            menuItem.description = descriptionTextarea.value;
                        }
                        
                        // 检查下一个元素是否为子菜单容器
                        let nextElement = currentElement.nextElementSibling;
                        if (nextElement && nextElement.classList.contains('sub-menu')) {
                            // 递归处理子菜单
                            menuItem.children = buildMenuStructure(nextElement);
                            // 跳过子菜单容器，继续处理下一个菜单项
                            currentElement = nextElement.nextElementSibling;
                        } else {
                            currentElement = nextElement;
                        }
                        
                        items.push(menuItem);
                    } else {
                        currentElement = currentElement.nextElementSibling;
                    }
                }
                
                return items;
            }

            // 从根容器开始构建
            newMenuItems = buildMenuStructure(container);
            menuItems = newMenuItems;
            console.log('菜单数据已更新:', menuItems);
        }

        // 加载菜单
        function loadMenu() {
            const menuSelect = document.getElementById('menuSelect');
            currentMenu = menuSelect.value;

            // 更新菜单名称输入框
            const menuNameInput = document.getElementById('menuName');
            if (menuNameInput) {
                menuNameInput.value = currentMenu;
            }

            // 调用后端API加载菜单数据
            fetch(`/admin/sys/options/menu/load/${currentMenu}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        console.log('加载菜单成功:', data);
                        renderMenuFromData(data.data.items);
                    } else {
                        console.log('菜单不存在，创建新菜单');
                        // 如果菜单不存在，创建空菜单
                        menuItems = [];
                        nextItemId = 1;
                        const container = document.getElementById('menuItemsContainer');
                        if (container) {
                            container.innerHTML = '';
                        }
                    }
                })
                .catch(error => {
                    console.error('加载菜单失败:', error);
                    // 加载失败时创建空菜单
                    menuItems = [];
                    nextItemId = 1;
                    const container = document.getElementById('menuItemsContainer');
                    if (container) {
                        container.innerHTML = '';
                    }
                });
        }

        // 从数据渲染菜单
        function renderMenuFromData(items) {
            const container = document.getElementById('menuItemsContainer');
            if (!container) return;
            
            // 清空现有内容
            container.innerHTML = '';
            
            // 重置数据（使用临时变量避免影响全局状态）
            const tempMenuItems = [];
            let tempNextItemId = 1;
            
            // 递归渲染菜单项
            function renderMenuItem(item, parentContainer) {
                const menuItem = createMenuItemFromData(item);
                parentContainer.appendChild(menuItem);
                
                // 如果有子菜单，创建子菜单容器并递归渲染
                if (item.children && item.children.length > 0) {
                    const submenuContainer = document.createElement('div');
                    submenuContainer.className = 'sub-menu';
                    
                    item.children.forEach(childItem => {
                        renderMenuItem(childItem, submenuContainer);
                    });
                    
                    parentContainer.appendChild(submenuContainer);
                }
            }
            
            // 渲染所有顶级菜单项
            items.forEach(item => {
                renderMenuItem(item, container);
            });
            
            // 重新初始化拖拽功能
            initDragAndDrop();
            
            // 更新子菜单标签
            updateSubmenuLabels();
        }

        // 从数据创建菜单项元素
        function createMenuItemFromData(item) {
            const menuItem = document.createElement('div');
            menuItem.className = 'menu-item';
            menuItem.setAttribute('data-id', item.id);
            menuItem.setAttribute('data-type', item.type || 'custom-link');
            
            const title = item.title || item.navigation_label || '未命名菜单项';
            const url = item.url || item.href || '#';
            const navigationLabel = item.navigation_label || title;
            const target = item.target || '_self';
            
            menuItem.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle" style="cursor: move; margin-right: 10px; color: #999;">⋮⋮</div>
                    <div class="menu-item-title">${title}</div>
                    <div class="menu-item-type">${getMenuItemTypeName(item.type)}</div>
                    <div class="menu-item-actions">
                        <button class="menu-item-action" onclick="toggleMenuItem(this)" title="展开/收起">▼</button>
                        <button class="menu-item-action" onclick="removeMenuItem(this)" title="删除">×</button>
                    </div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="${navigationLabel}">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="${url}">
                    </div>
                    <div class="form-group">
                        <label>图标:</label>
                        <input type="text" placeholder="图标类名或URL" value="${item.icon || ''}">
                    </div>
                    <div class="form-group">
                        <label>Target:</label>
                        <select name="target">
                            <option value="_self" ${target === '_self' ? 'selected' : ''}>当前窗口 (_self)</option>
                            <option value="_blank" ${target === '_blank' ? 'selected' : ''}>新窗口 (_blank)</option>
                            <option value="_parent" ${target === '_parent' ? 'selected' : ''}>父窗口 (_parent)</option>
                            <option value="_top" ${target === '_top' ? 'selected' : ''}>顶级窗口 (_top)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>标题属性:</label>
                        <input type="text" placeholder="鼠标悬停时显示的文本" value="${item.title_attribute || ''}">
                    </div>
                    <div class="form-group">
                        <label>CSS类:</label>
                        <input type="text" placeholder="CSS类名" value="${item.css_classes || ''}">
                    </div>
                    <div class="form-group">
                        <label>链接关系(XFN):</label>
                        <input type="text" placeholder="链接关系" value="${item.xfn || ''}">
                    </div>
                    <div class="form-group">
                        <label>描述:</label>
                        <textarea rows="3" placeholder="菜单项描述">${item.description || ''}</textarea>
                    </div>
                </div>
            `;
            
            return menuItem;
        }

        // 获取菜单项类型名称
        function getMenuItemTypeName(type) {
            const typeNames = {
                'custom-link': '自定义链接',
                'page': '页面',
                'post': '文章',
                'category': '分类目录'
            };
            return typeNames[type] || '自定义链接';
        }

        // 清空菜单结构
        function clearMenuStructure() {
            const container = document.getElementById('menuItemsContainer');
            if (container) {
                container.innerHTML = '';
                console.log('菜单结构已清空');
            }
            const menuName = document.getElementById('menuName');
            if (menuName) {
                menuName.value = '';
                console.log('菜单名称已清空');
            }
            // 重置菜单数据
            menuItems = [];
            nextItemId = 1;
        }

        // 创建新菜单
        function createNewMenu() {

            // 清空菜单结构
            clearMenuStructure();

        }

        // 保存菜单
        function saveMenu() {
            const menuName = document.getElementById('menuName').value;
            if (!menuName.trim()) {
                alert('请输入菜单名称');
                return;
            }
            
            // 更新菜单数据
            updateMenuData();
            
            const menuData = {
                name: menuName,
                items: menuItems
            };

            // 显示保存中状态
            const saveButton = document.querySelector('.btn-primary');
            const originalText = saveButton.textContent;
            saveButton.textContent = '保存中...';
            saveButton.disabled = true;

            // 调用后端API保存菜单
            fetch('/admin/sys/options/menu/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(menuData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    console.log('菜单保存成功:', data);
                    
                    // 保存成功后刷新菜单列表
                    loadMenuList();
                } else {
                    alert('保存失败: ' + data.message);
                    console.error('菜单保存失败:', data);
                }
            })
            .catch(error => {
                alert('保存失败: ' + error.message);
                console.error('保存菜单时发生错误:', error);
            })
            .finally(() => {
                // 恢复按钮状态
                saveButton.textContent = originalText;
                saveButton.disabled = false;
            });
        }

        // 删除菜单
        function deleteMenu() {
            const menuName = document.getElementById('menuName').value;
            if (!menuName.trim()) {
                alert('请输入菜单名称');
                return;
            }
            
            if (confirm(`确定要删除菜单 "${menuName}" 吗？`)) {
                // 显示删除中状态
                const deleteButton = document.querySelector('.btn-danger');
                const originalText = deleteButton.textContent;
                deleteButton.textContent = '删除中...';
                deleteButton.disabled = true;

                // 调用后端API删除菜单
                fetch(`/admin/sys/options/menu/delete/${menuName}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        console.log('菜单删除成功:', data);
                        
                        // 清空菜单结构
                        const container = document.getElementById('menuItemsContainer');
                        if (container) {
                            container.innerHTML = '';
                        }

                                    // 注意：不重置全局变量，避免影响其他函数
                        
                        // 清空菜单名称
                        document.getElementById('menuName').value = '';
                    } else {
                        alert('删除失败: ' + data.message);
                        console.error('菜单删除失败:', data);
                    }
                })
                .catch(error => {
                    alert('删除失败: ' + error.message);
                    console.error('删除菜单时发生错误:', error);
                })
                .finally(() => {
                    // 恢复按钮状态
                    deleteButton.textContent = originalText;
                    deleteButton.disabled = false;
                });
            }
        }

        // 加载菜单数据
        function loadMenuData() {
            // 这里可以调用后端API获取菜单数据
            console.log('加载菜单数据:', currentMenu);

            // 模拟数据加载
            // 实际实现时，这里会从后端获取数据并渲染到界面
        }

        // 加载菜单列表
        function loadMenuList() {
            fetch('/admin/sys/options/menu/list')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateMenuSelect(data.data);
                    } else {
                        console.error('加载菜单列表失败:', data.message);
                    }
                })
                .catch(error => {
                    console.error('加载菜单列表时发生错误:', error);
                });
        }

        // 更新菜单选择下拉框
        function updateMenuSelect(menus) {
            const menuSelect = document.getElementById('menuSelect');
            if (!menuSelect) return;
            
            // 保存当前选中的值
            const currentValue = menuSelect.value;
            
            // 清空现有选项
            menuSelect.innerHTML = '';
            
            // 添加默认菜单选项
            const defaultMenus = [
                { name: 'primary', display: 'primary (主要)' },
                { name: 'footer', display: 'footer (页脚)' },
                { name: 'mobile', display: 'mobile (移动端)' }
            ];
            
            // 添加默认菜单
            defaultMenus.forEach(menu => {
                const option = document.createElement('option');
                option.value = menu.name;
                option.textContent = menu.display;
                menuSelect.appendChild(option);
            });
            
            // 添加从数据库加载的菜单
            menus.forEach(menu => {
                // 检查是否已经存在该菜单
                const existingOption = menuSelect.querySelector(`option[value="${menu.name}"]`);
                if (!existingOption) {
                    const option = document.createElement('option');
                    option.value = menu.name;
                    option.textContent = `${menu.name} (${menu.items_count} 项)`;
                    menuSelect.appendChild(option);
                }
            });
            
            // 恢复之前选中的值，如果不存在则选择第一个
            if (currentValue && menuSelect.querySelector(`option[value="${currentValue}"]`)) {
                menuSelect.value = currentValue;
            } else if (menuSelect.options.length > 0) {
                menuSelect.value = menuSelect.options[0].value;
            }
        }

        // 预留的后端接口调用函数
        function callBackendAPI(endpoint, data) {
            // 这里实现与后端的API调用
            console.log('调用后端API:', endpoint, data);

            // 示例：使用fetch调用后端API
            /*
            return fetch(`/api/menu/${endpoint}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .catch(error => {
                console.error('API调用失败:', error);
                throw error;
            });
            */
        }

        // 测试拖拽功能
        function testDragAndDrop() {
            const items = document.querySelectorAll('.menu-item');
            console.log('拖拽功能测试完成！');
            console.log('找到', items.length, '个菜单项');
            console.log('请查看控制台获取详细信息');
        }

        // 测试子父级拖拽功能
        function testSubmenuDrag() {
            const items = document.querySelectorAll('.menu-item');
            const submenus = document.querySelectorAll('.sub-menu');
            console.log('子父级拖拽功能测试完成！');
            console.log('找到', items.length, '个菜单项，', submenus.length, '个子菜单');
            console.log('请查看控制台获取详细信息');
        }

        // 创建测试菜单结构
        function createTestMenuStructure() {
            const container = document.getElementById('menuItemsContainer');
            
            // 清空现有内容
            container.innerHTML = '';
            
            // 创建测试菜单项
            const testItems = [
                { id: 1, title: '首页', type: 'custom-link', url: '/' },
                { id: 2, title: '关于我们', type: 'custom-link', url: '/about' },
                { id: 3, title: '产品服务', type: 'custom-link', url: '/services' },
                { id: 4, title: '新闻资讯', type: 'custom-link', url: '/news' },
                { id: 5, title: '联系我们', type: 'custom-link', url: '/contact' }
            ];
            
            testItems.forEach(item => {
                const menuItem = createMenuItemElement(item);
                container.appendChild(menuItem);
            });
            
            // 重新初始化拖拽功能
            initDragAndDrop();
            
            console.log('测试菜单结构已创建，包含5个菜单项');
            console.log('请尝试拖拽菜单项来测试携带子菜单一起移动的功能');
        }

        // 切换页面标签页
        function switchPageTab(tabElement, tabName) {
            // 移除所有标签页的active类
            document.querySelectorAll('.page-tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 隐藏所有标签页内容
            document.querySelectorAll('.page-tab-content').forEach(content => {
                content.style.display = 'none';
            });

            // 激活当前标签页
            tabElement.classList.add('active');

            // 显示对应的内容
            const contentId = tabName + '-pages';
            const content = document.getElementById(contentId);
            if (content) {
                content.style.display = 'block';
            }
        }

        // 全选/取消全选
        function toggleSelectAll(tabName) {
            const selectAllCheckbox = document.getElementById('select-all-' + tabName);
            const pageItems = document.querySelectorAll('#' + tabName + '-pages .page-item input[type="checkbox"]');

            pageItems.forEach(item => {
                item.checked = selectAllCheckbox.checked;
            });
        }

        // 添加选中的页面到菜单
        function addSelectedPages(tabName) {
            const checkedItems = document.querySelectorAll('#' + tabName + '-pages .page-item input[type="checkbox"]:checked');

            if (checkedItems.length === 0) {
                return;
            }

            checkedItems.forEach(item => {
                const type = item.getAttribute('data-type');
                const id = item.getAttribute('data-id');
                const title = item.getAttribute('data-title');

                const menuItem = {
                    id: nextItemId++,
                    type: type,
                    title: title,
                    url: '/page/' + id,
                    navigation_label: title,
                    target: '_self', // 默认在当前窗口打开
                    icon: '',
                    title_attribute: '',
                    css_classes: '',
                    xfn: '',
                    description: '',
                    parent: null
                };

                addMenuItemToStructure(menuItem);
            });

            // 取消选中状态
            checkedItems.forEach(item => {
                item.checked = false;
            });

            // 取消全选状态
            const selectAllCheckbox = document.getElementById('select-all-' + tabName);
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = false;
            }
        }

        // 搜索页面
        function searchPages(keyword) {
            const searchResults = document.getElementById('search-results');
            const allPages = [
                {% for page in get_pages() %}
                {
                    slug: '{{ page.slug }}',
                    title: '{{ page.title | escape }}'
                }{% if not loop.last %},{% endif %}
                {% endfor %}
            ];
            {#const allPages = [#}
            {#    { slug: 'home', title: '首页' },#}
            {#    { slug: 'about', title: '关于我们' }]#}

            if (!keyword.trim()) {
                // 显示所有页面
                searchResults.innerHTML = allPages.map(page => `
                    <div class="page-item">
                        <input type="checkbox" id="page-search-${page.slug}" data-type="page" data-id="${page.slug}" data-title="${page.title}">
                        <label for="page-search-${page.slug}">${page.title}</label>
                    </div>
                `).join('');
                return;
            }

            // 过滤页面
            const filteredPages = allPages.filter(page =>
                page.title.toLowerCase().includes(keyword)
            );

            if (filteredPages.length === 0) {
                searchResults.innerHTML = '<div style="padding: 20px; text-align: center; color: #666;">未找到匹配的页面</div>';
            } else {
                searchResults.innerHTML = filteredPages.map(page => `
                    <div class="page-item">
                        <input type="checkbox" id="page-search-${page.slug}" data-type="page" data-id="${page.slug}" data-title="${page.title}">
                        <label for="page-search-${page.slug}">${page.title}</label>
                    </div>
                `).join('');
            }
        }

        // 切换文章标签页
        function switchPostTab(tabElement, tabName) {
            // 移除所有标签页的active类
            document.querySelectorAll('.post-tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 隐藏所有标签页内容
            document.querySelectorAll('.post-tab-content').forEach(content => {
                content.style.display = 'none';
            });

            // 激活当前标签页
            tabElement.classList.add('active');

            // 显示对应的内容
            const contentId = tabName + '-posts';
            const content = document.getElementById(contentId);
            if (content) {
                content.style.display = 'block';
            }
        }

        // 全选/取消全选文章
        function toggleSelectAllPosts(tabName) {
            const selectAllCheckbox = document.getElementById('select-all-' + tabName + '-posts');
            const postItems = document.querySelectorAll('#' + tabName + '-posts .post-item input[type="checkbox"]');

            postItems.forEach(item => {
                item.checked = selectAllCheckbox.checked;
            });
        }

        // 添加选中的文章到菜单
        function addSelectedPosts(tabName) {
            const checkedItems = document.querySelectorAll('#' + tabName + '-posts .post-item input[type="checkbox"]:checked');

            if (checkedItems.length === 0) {
                return;
            }

            checkedItems.forEach(item => {
                const type = item.getAttribute('data-type');
                const id = item.getAttribute('data-id');
                const title = item.getAttribute('data-title');

                const menuItem = {
                    id: nextItemId++,
                    type: type,
                    title: title,
                    url: '/post/' + id,
                    navigation_label: title,
                    target: '_self', // 默认在当前窗口打开
                    icon: '',
                    title_attribute: '',
                    css_classes: '',
                    xfn: '',
                    description: '',
                    parent: null
                };

                addMenuItemToStructure(menuItem);
            });

            // 取消选中状态
            checkedItems.forEach(item => {
                item.checked = false;
            });

            // 取消全选状态
            const selectAllCheckbox = document.getElementById('select-all-' + tabName + '-posts');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = false;
            }
        }

        // 搜索文章
        function searchPosts(keyword) {
            const searchResults = document.getElementById('post-search-results');
            const allPosts = [
                    {% for post in get_articles() %}
                    {
                        slug: '{{ post.slug }}',
                        title: '{{ post.title | escape }}'
                    }{% if not loop.last %},{% endif %}
                    {% endfor %}
                ];

            if (!keyword.trim()) {
                // 显示所有文章
                searchResults.innerHTML = allPosts.map(post => `
                    <div class="post-item">
                        <input type="checkbox" id="post-search-${post.slug}" data-type="post" data-id="${post.slug}" data-title="${post.title}">
                        <label for="post-search-${post.slug}">${post.title}</label>
                    </div>
                `).join('');
                return;
            }

            // 过滤文章
            const filteredPosts = allPosts.filter(post =>
                post.title.toLowerCase().includes()
            );

            if (filteredPosts.length === 0) {
                searchResults.innerHTML = '<div style="padding: 20px; text-align: center; color: #666;">未找到匹配的文章</div>';
            } else {
                searchResults.innerHTML = filteredPosts.map(post => `
                    <div class="post-item">
                        <input type="checkbox" id="post-search-${post.slug}" data-type="post" data-id="${post.slug}" data-title="${post.title}">
                        <label for="post-search-${post.slug}">${post.title}</label>
                    </div>
                `).join('');
            }
        }

        // 切换分类目录标签页
        function switchCategoryTab(tabElement, tabName) {
            // 移除所有标签页的active类
            document.querySelectorAll('.category-tab').forEach(tab => {
                tab.classList.remove('active');
            });

            // 隐藏所有标签页内容
            document.querySelectorAll('.category-tab-content').forEach(content => {
                content.style.display = 'none';
            });

            // 激活当前标签页
            tabElement.classList.add('active');

            // 显示对应的内容
            const contentId = tabName + '-categories';
            const content = document.getElementById(contentId);
            if (content) {
                content.style.display = 'block';
            }
        }

        // 全选/取消全选分类目录
        function toggleSelectAllCategories(tabName) {
            const selectAllCheckbox = document.getElementById('select-all-' + tabName + '-categories');
            const categoryItems = document.querySelectorAll('#' + tabName + '-categories .category-item input[type="checkbox"]');

            categoryItems.forEach(item => {
                item.checked = selectAllCheckbox.checked;
            });
        }

        // 添加选中的分类目录到菜单
        function addSelectedCategories(tabName) {
            const checkedItems = document.querySelectorAll('#' + tabName + '-categories .category-item input[type="checkbox"]:checked');

            if (checkedItems.length === 0) {
                return;
            }

            checkedItems.forEach(item => {
                const type = item.getAttribute('data-type');
                const id = item.getAttribute('data-id');
                const title = item.getAttribute('data-title');

                const menuItem = {
                    id: nextItemId++,
                    type: type,
                    title: title,
                    url: '/category/' + id,
                    parent: null
                };

                addMenuItemToStructure(menuItem);
            });

            // 取消选中状态
            checkedItems.forEach(item => {
                item.checked = false;
            });

            // 取消全选状态
            const selectAllCheckbox = document.getElementById('select-all-' + tabName + '-categories');
            if (selectAllCheckbox) {
                selectAllCheckbox.checked = false;
            }

        }

        // 搜索分类目录
        function searchCategories(keyword) {
            const searchResults = document.getElementById('category-search-results');

            const allCategories = [
                {% for category in get_categories() %}
                {
                    alias: '{{ category.alias }}',
                    title: '{{ category.title | escape }}'
                }{% if not loop.last %},{% endif %}
                {% endfor %}
            ];

            if (!keyword.trim()) {
                // 显示所有分类目录
                searchResults.innerHTML = allCategories.map(category => `
                    <div class="category-item">
                        <input type="checkbox" id="category-search-${category.alias}" data-type="category" data-id="${category.alias}" data-title="${category.title}">
                        <label for="category-search-${category.alias}">${category.title}</label>
                    </div>
                `).join('');
                return;
            }

            // 过滤分类目录
            const filteredCategories = allCategories.filter(category =>
                category.title.toLowerCase().includes(keyword)
            );

            if (filteredCategories.length === 0) {
                searchResults.innerHTML = '<div style="padding: 20px; text-align: center; color: #666;">未找到匹配的分类目录</div>';
            } else {
                searchResults.innerHTML = filteredCategories.map(category => `
                    <div class="category-item">
                        <input type="checkbox" id="category-search-${category.alias}" data-type="category" data-id="${category.alias}" data-title="${category.title}">
                        <label for="category-search-${category.alias}">${category.title}</label>
                    </div>
                `).join('');
            }
        }

        // 测试展开/收起功能
        function testToggleSection() {
            console.log('Testing toggle section...');
            const customLinkSection = document.querySelector('.menu-item-section');
            const header = customLinkSection.querySelector('.menu-item-section-header');
            console.log('Found custom link section:', customLinkSection);
            console.log('Found header:', header);
            toggleSection(header);
        }

        // 测试自定义链接功能
        function testCustomLink() {
            console.log('Testing custom link...');
            const urlInput = document.getElementById('customLinkUrl');
            const textInput = document.getElementById('customLinkText');
            console.log('URL input:', urlInput);
            console.log('Text input:', textInput);
            if (urlInput && textInput) {
                urlInput.value = 'https://example.com';
                textInput.value = '测试链接';
                console.log('Set test values');
            }
        }

        // 测试菜单数据结构
        function testMenuDataStructure() {
            const testData = [
                {
                    id: 1,
                    title: '首页',
                    type: 'custom-link',
                    url: '/',
                    children: [
                        {
                            id: 2,
                            title: '子页面1',
                            type: 'page',
                            url: '/subpage1',
                            children: [
                                {
                                    id: 3,
                                    title: '孙页面1',
                                    type: 'page',
                                    url: '/subpage1/grandchild1'
                                }
                            ]
                        },
                        {
                            id: 4,
                            title: '子页面2',
                            type: 'page',
                            url: '/subpage2'
                        }
                    ]
                },
                {
                    id: 5,
                    title: '关于我们',
                    type: 'custom-link',
                    url: '/about'
                }
            ];
            
            console.log('测试菜单数据结构:', testData);
            renderMenuFromData(testData);
        }

        // 测试保存和加载功能
        function testSaveAndLoad() {
            // 创建测试菜单结构
            createTestMenuStructure();
            
            // 等待DOM更新
            setTimeout(() => {
                // 保存菜单
                const menuNameInput = document.getElementById('menuName');
                if (menuNameInput) {
                    menuNameInput.value = 'test_menu';
                }
                
                updateMenuData();
                console.log('保存前的菜单数据:', menuItems);
                
                // 清空容器
                const container = document.getElementById('menuItemsContainer');
                if (container) {
                    container.innerHTML = '';
                }
                
                // 重新渲染
                renderMenuFromData(menuItems);
                console.log('重新渲染后的菜单数据:', menuItems);
            }, 100);
        }

        // 测试子菜单不关联问题
        function testSubmenuDisconnection() {
            console.log('=== 测试子菜单不关联问题 ===');
            
            // 创建测试菜单结构
            const container = document.getElementById('menuItemsContainer');
            container.innerHTML = '';
            
            // 创建父菜单项
            const parentMenu = document.createElement('div');
            parentMenu.className = 'menu-item';
            parentMenu.setAttribute('data-id', '1');
            parentMenu.setAttribute('data-type', 'custom-link');
            parentMenu.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="menu-item-title">父菜单</div>
                    <div class="menu-item-type">自定义链接</div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="父菜单">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="/parent">
                    </div>
                </div>
            `;
            
            // 创建第一个子菜单容器
            const submenu1 = document.createElement('div');
            submenu1.className = 'sub-menu';
            
            // 创建第一个子菜单项
            const child1 = document.createElement('div');
            child1.className = 'menu-item';
            child1.setAttribute('data-id', '2');
            child1.setAttribute('data-type', 'page');
            child1.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="menu-item-title">现有子菜单1</div>
                    <div class="menu-item-type">页面</div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="现有子菜单1">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="/child1">
                    </div>
                </div>
            `;
            
            submenu1.appendChild(child1);
            
            // 创建第二个子菜单项
            const child2 = document.createElement('div');
            child2.className = 'menu-item';
            child2.setAttribute('data-id', '3');
            child2.setAttribute('data-type', 'page');
            child2.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="menu-item-title">现有子菜单2</div>
                    <div class="menu-item-type">页面</div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="现有子菜单2">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="/child2">
                    </div>
                </div>
            `;
            
            submenu1.appendChild(child2);
            
            // 创建要拖拽的新菜单项（包含自己的子菜单）
            const newMenu = document.createElement('div');
            newMenu.className = 'menu-item';
            newMenu.setAttribute('data-id', '4');
            newMenu.setAttribute('data-type', 'custom-link');
            newMenu.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="menu-item-title">新拖拽菜单</div>
                    <div class="menu-item-type">自定义链接</div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="新拖拽菜单">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="/new">
                    </div>
                </div>
            `;
            
            // 创建新菜单的子菜单容器
            const newSubmenu = document.createElement('div');
            newSubmenu.className = 'sub-menu';
            
            // 创建新菜单的子菜单项
            const newChild = document.createElement('div');
            newChild.className = 'menu-item';
            newChild.setAttribute('data-id', '5');
            newChild.setAttribute('data-type', 'page');
            newChild.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="menu-item-title">新菜单的子菜单</div>
                    <div class="menu-item-type">页面</div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="新菜单的子菜单">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="/new/child">
                    </div>
                </div>
            `;
            
            newSubmenu.appendChild(newChild);
            
            // 组装初始结构
            container.appendChild(parentMenu);
            container.appendChild(submenu1);
            container.appendChild(newMenu);
            container.appendChild(newSubmenu);
            
            // 初始化拖拽功能
            initDragAndDrop();
            
            console.log('初始菜单结构已创建');
            console.log('父菜单下现有子菜单数量:', submenu1.children.length);
            console.log('新菜单下子菜单数量:', newSubmenu.children.length);
            
            // 模拟将新菜单拖拽到父菜单下
            console.log('模拟拖拽操作...');
            createSubmenu(parentMenu, newMenu);
            
            console.log('拖拽操作完成');
            const finalSubmenu = parentMenu.nextElementSibling;
            console.log('父菜单下现在子菜单数量:', finalSubmenu.children.length);
            console.log('最终子菜单项:', Array.from(finalSubmenu.children).map(child => child.querySelector('.menu-item-title').textContent));
            
            // 检查是否有多个子菜单容器
            const allSubmenus = container.querySelectorAll('.sub-menu');
            console.log('总子菜单容器数量:', allSubmenus.length);
            
            if (allSubmenus.length > 1) {
                console.error('❌ 问题重现：存在多个子菜单容器，导致不关联');
            } else {
                console.log('✅ 成功：所有子菜单都在同一个容器中');
            }
        }

        // 修复子菜单不关联问题的函数
        function fixSubmenuDisconnection() {
            console.log('=== 修复子菜单不关联问题 ===');
            
            const container = document.getElementById('menuItemsContainer');
            
            // 检查是否有多个子菜单容器属于同一个父菜单
            const menuItems = container.querySelectorAll('.menu-item');
            menuItems.forEach(menuItem => {
                const submenus = [];
                let nextElement = menuItem.nextElementSibling;
                
                // 收集该菜单项后面的所有子菜单容器
                while (nextElement && nextElement.classList.contains('sub-menu')) {
                    submenus.push(nextElement);
                    nextElement = nextElement.nextElementSibling;
                }
                
                // 如果有多个子菜单容器，合并它们
                if (submenus.length > 1) {
                    console.log(`发现菜单项 "${menuItem.querySelector('.menu-item-title').textContent}" 有 ${submenus.length} 个子菜单容器，正在合并...`);
                    
                    const firstSubmenu = submenus[0];
                    
                    // 将其他子菜单容器中的项目移动到第一个容器
                    for (let i = 1; i < submenus.length; i++) {
                        const submenu = submenus[i];
                        const items = Array.from(submenu.children);
                        items.forEach(item => {
                            firstSubmenu.appendChild(item);
                        });
                        submenu.remove();
                    }
                    
                    console.log('子菜单容器合并完成');
                }
            });
            
            // 更新子菜单标签
            updateSubmenuLabels();
            console.log('子菜单不关联问题已修复');
        }

        // 测试新菜单创建功能
        function testCreateNewMenu() {
            console.log('=== 测试新菜单创建功能 ===');
            
            // 模拟创建新菜单
            console.log('当前菜单:', currentMenu);
            console.log('当前菜单项数量:', menuItems.length);
            
            // 清空菜单结构
            clearMenuStructure();
            
            console.log('清空后菜单项数量:', menuItems.length);
            console.log('菜单结构已清空，可以开始创建新菜单');
            
            // 显示提示信息
            alert('菜单结构已清空，请点击"或创建一个新菜单"来创建新菜单');
        }

        // 验证菜单结构是否为空
        function isMenuStructureEmpty() {
            const container = document.getElementById('menuItemsContainer');
            if (!container) return true;
            
            return container.children.length === 0;
        }

        // 获取当前菜单信息
        function getCurrentMenuInfo() {
            return {
                name: currentMenu,
                itemsCount: menuItems.length,
                isEmpty: isMenuStructureEmpty(),
                nextItemId: nextItemId
            };
        }

        // 测试Target字段功能
        function testTargetField() {
            console.log('=== 测试Target字段功能 ===');
            
            // 创建测试菜单结构
            const container = document.getElementById('menuItemsContainer');
            container.innerHTML = '';
            
            // 创建测试菜单项
            const testMenuItem = document.createElement('div');
            testMenuItem.className = 'menu-item';
            testMenuItem.setAttribute('data-id', '1');
            testMenuItem.setAttribute('data-type', 'custom-link');
            testMenuItem.innerHTML = `
                <div class="menu-item-header">
                    <div class="drag-handle">⋮⋮</div>
                    <div class="menu-item-title">外部链接</div>
                    <div class="menu-item-type">自定义链接</div>
                </div>
                <div class="menu-item-content">
                    <div class="form-group">
                        <label>导航标签:</label>
                        <input type="text" value="外部链接">
                    </div>
                    <div class="form-group">
                        <label>URL:</label>
                        <input type="url" value="https://example.com">
                    </div>
                    <div class="form-group">
                        <label>图标:</label>
                        <input type="text" placeholder="图标类名或URL" value="fa fa-external-link">
                    </div>
                    <div class="form-group">
                        <label>Target:</label>
                        <select name="target">
                            <option value="_self">当前窗口 (_self)</option>
                            <option value="_blank" selected>新窗口 (_blank)</option>
                            <option value="_parent">父窗口 (_parent)</option>
                            <option value="_top">顶级窗口 (_top)</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>标题属性:</label>
                        <input type="text" placeholder="鼠标悬停时显示的文本" value="在新窗口中打开">
                    </div>
                    <div class="form-group">
                        <label>CSS类:</label>
                        <input type="text" placeholder="CSS类名" value="external-link">
                    </div>
                    <div class="form-group">
                        <label>链接关系(XFN):</label>
                        <input type="text" placeholder="链接关系" value="nofollow">
                    </div>
                    <div class="form-group">
                        <label>描述:</label>
                        <textarea rows="3" placeholder="菜单项描述">外部链接，在新窗口中打开</textarea>
                    </div>
                </div>
            `;
            
            container.appendChild(testMenuItem);
            
            console.log('测试菜单项已创建');
            console.log('现在测试updateMenuData函数...');
            
            // 测试updateMenuData
            updateMenuData();
            
            console.log('updateMenuData完成，检查结果...');
            console.log('菜单数据:', menuItems);
            
            // 验证Target字段是否被保存
            if (menuItems.length > 0) {
                const item = menuItems[0];
                console.log('验证Target字段:');
                console.log('- Target值:', item.target);
                
                if (item.target === '_blank') {
                    console.log('✅ 成功：Target字段被正确保存');
                } else {
                    console.error('❌ 失败：Target字段未被正确保存');
                }
            } else {
                console.error('❌ 失败：没有菜单数据');
            }
        }

        // 获取Target选项的显示文本
        function getTargetDisplayText(target) {
            const targetOptions = {
                '_self': '当前窗口 (_self)',
                '_blank': '新窗口 (_blank)',
                '_parent': '父窗口 (_parent)',
                '_top': '顶级窗口 (_top)'
            };
            return targetOptions[target] || '当前窗口 (_self)';
        }

        // 验证Target值是否有效
        function isValidTarget(target) {
            const validTargets = ['_self', '_blank', '_parent', '_top'];
            return validTargets.includes(target);
        }
    </script>
</body>
{% include 'system/common/footer.html' %}
</html>